import 'package:chathouse/pages/expert/buyWallet/wallet_cer_detail.dart';
import 'package:chathouse/pages/widgets/down_menu_items.dart';
import 'package:chathouse/public/Config.dart';
import 'package:chathouse/util/base_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../../model/wallet_cel.dart';
import '../../../public/empty_widget.dart';
import '../../base/base.dart';
import '../../widgets/down_item.dart';

// 充值记录
class WalletCerListPage extends BaseStatefulWidget {
  const WalletCerListPage({Key? key}) : super(key: key);

  @override
  _WalletCerListPageState createState() => _WalletCerListPageState();
}

class _WalletCerListPageState
    extends BaseStatefulWidgetState<WalletCerListPage> {
  WalletCerList? cerList;
  List<CMenuItem>? dataList;
  String seleValue = "";

  final RefreshController _refreshController =
      RefreshController(initialRefresh: true); // 刷新控件控制

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    setState(() {
      updateState(LoadState.success);
      showAppBar = true;
      appBarTitle = "充值記錄";
      leading = const Icon(
        Icons.arrow_back_ios_rounded,
        color: Styles.c_666,
      );
    });
    getData();
    load();
  }

  void load() {
    Obj.showLoading();
    final map = {
      "createTime": seleValue,
    };
    Apis.cerList(map)
        .then((response) => {
              _refreshController.refreshCompleted(),
              Obj.dismissLoading(),
              setState(() {
                var data = response?.data;
                cerList = WalletCerList.fromJson(data);
                if (cerList?.data?.list?.isEmpty == true) {}
                setState(() {});
              })
            })
        .onError((error, stackTrace) =>
            {_refreshController.refreshCompleted(), Obj.dismissLoading()});
  }

  void changeSelectValue(value) {
    seleValue = value;
    load();
    setState(() {});
  }

  void getData() {
    dataList = [];
    var time = DateTime.now();
    int month = time.month;
    int year = time.year;
    seleValue = month < 10 ? "${year}-0${month}" : "${year}-${month}";

    dataList = getPreviousSixMonths();
    setState(() {});
  }

  List<CMenuItem> getPreviousSixMonths() {
    DateTime currentDate = DateTime.now();
    List<CMenuItem> previousMonths = [];
    for (int i = 0; i <= 6; i++) {
      DateTime previousMonthDate = currentDate.subtract(Duration(days: 30 * i));
      String formattedDate = DateFormat('yyyy-MM').format(previousMonthDate);
      CMenuItem item = CMenuItem(label: formattedDate, value: formattedDate);
      previousMonths.add(item);
    }
    return previousMonths;
  }

  Widget item(CerItem? row) {
    String name = "";
    Color nameColor = Styles.c_191919;
    // ignore: unrelated_type_equality_checks
    if (row?.serviceState == "0") {
      name = "待驗證";
      nameColor = Styles.c_FF9090;
    }
    // ignore: unrelated_type_equality_checks
    if (row?.serviceState == "1") {
      name = "成功";
      nameColor = Styles.subMainColor;
    }
    // ignore: unrelated_type_equality_checks
    if (row?.serviceState == "2") {
      name = "失败";
      nameColor = Styles.color_F93A4A;
    }
    return Slidable(
      enabled: row?.serviceState == "0" ? false : true,
      endActionPane: ActionPane(
        //滑动选项面板
        motion: const StretchMotion(), //滑动动画
        extentRatio: 0.3,
        children: [
          SlidableAction(
              onPressed: (context) {
                Get.to(WalletCerDetail(row));
              },
              spacing: 0,
              //触发删除的函数
              icon: Icons.info,
              //图标
              label: "反饋",
              padding: EdgeInsets.all(0),
              backgroundColor: Styles.c_f5f5f7,
              foregroundColor: Styles.mainColor)
        ],
      ),
      child: Container(
        height: 86.w,
        padding: EdgeInsets.symmetric(horizontal: 30.w),
        color: Colors.white,
        child: Row(
          children: [
            Container(
              width: 96.w,
              color: Colors.white,
              child: Column(
                children: [
                  Expanded(
                      child: Container(
                    alignment: Alignment.centerLeft,
                    child: Text(
                      name,
                      style: getTextStyle(20.w,
                          fontType: FontType.BOLD, color: nameColor),
                    ),
                  )),
                  Expanded(child: Container()),
                ],
              ),
            ),
            Expanded(
                child: Column(
              children: [
                Expanded(
                    child: Container(
                  color: Colors.white,
                  child: Row(
                    children: [
                      Text(row?.serviceContent ?? '',
                          style: getTextStyle(20.w,
                              fontType: FontType.BOLD, color: Styles.c_191919)),
                      Expanded(
                          child: Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: [
                          Text("-\$${row?.money ?? ''}",
                              style: getTextStyle(20.w,
                                  fontType: FontType.BOLD,
                                  color: Styles.c_191919)),
                          const Icon(
                            Icons.chevron_right,
                            color: Styles.c_999,
                            size: 16,
                          ),
                        ],
                      ))
                    ],
                  ),
                )),
                Expanded(
                    child: Container(
                  padding: EdgeInsets.only(top: 8.w),
                  alignment: Alignment.topLeft,
                  color: Colors.white,
                  child: Text(row?.createTime ?? "",
                      style: getTextStyle(14.w, color: Styles.c_666)),
                )),
              ],
            ))
          ],
        ),
      ),
    );
  }

  Widget header() {
    return Container(
      height: 50,
      color: Colors.white,
      alignment: Alignment.center,
      padding: EdgeInsets.symmetric(horizontal: 30.w),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Row(
            children: [
              SelectWidget(
                items: List.generate(dataList?.length ?? 0, (index) {
                  return dataList![index];
                }),
                value: seleValue,
                valueChanged: changeSelectValue,
              ),
            ],
          ),
          Text(
            "總充值金額: \$${cerList?.data?.numGet ?? 0}",
            style: TextStyle(
                fontSize: 20.sp,
                fontWeight: FontWeight.w600,
                color: Styles.c_191919),
          ),
        ],
      ),
    );
  }

  @override
  AppBar viewAppBar() {
    return super.viewAppBar();
  }

  @override
  Widget viewPageBody() {
    return Scaffold(
      // appBar: getAppBar(title: "充值記錄"),
      body: SmartRefresher(
        enablePullDown: true,
        enablePullUp: false,
        controller: _refreshController,
        onRefresh: load,
        child: _buildContent(),
      ),
    );
  }

  Widget _buildContent() {
    return CustomScrollView(
      slivers: [
        SliverToBoxAdapter(
          child: Container(
            height: 50,
            color: Colors.white,
            alignment: Alignment.center,
            padding: EdgeInsets.symmetric(horizontal: 30.w),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Row(
                  children: [
                    SelectWidget(
                      items: List.generate(dataList?.length ?? 0, (index) {
                        return dataList![index];
                      }),
                      value: seleValue,
                      valueChanged: changeSelectValue,
                    ),
                  ],
                ),
                Text(
                  "總充值金額: \$${cerList?.data?.numGet ?? 0}",
                  style: TextStyle(
                      fontSize: 20.sp,
                      fontWeight: FontWeight.w600,
                      color: Styles.c_191919),
                ),
              ],
            ),
          ),
        ),
        cerList?.data?.list?.length == 0
            ? SliverToBoxAdapter(
                child: Container(
                    margin: EdgeInsets.only(top: 200.w),
                    width: 1.sw,
                    child: const EmptyWidget(
                      emptyText: "暫無數據",
                    )),
              )
            : SliverList(
                delegate: _buildTypeList(),
              )
      ],
    );
  }

  SliverChildDelegate _buildTypeList() {
    return SliverChildBuilderDelegate(
      (BuildContext context, int index) {
        return item(cerList?.data?.list?[index]).setOnClickListener(() {
          Get.to(WalletCerDetail(cerList?.data?.list?[index]));
        });
      },
      childCount: cerList?.data?.list?.length ?? 0,
    );
  }
}
